package com.novax.ex.activity.provider.controller.inner;

import cn.hutool.core.date.DateUtil;
import com.novax.ex.activity.infrastructure.entity.EventSignup;
import com.novax.ex.activity.infrastructure.entity.OperationConfig;
import com.novax.ex.activity.infrastructure.entity.OperationUserCount;
import com.novax.ex.activity.infrastructure.entity.OperationUserLog;
import com.novax.ex.activity.open.api.inner.OperationConfigInnerApi;
import com.novax.ex.activity.open.model.query.OperationConfigInnerQuery;
import com.novax.ex.activity.open.model.request.OperationConfigRequest;
import com.novax.ex.activity.open.model.response.OperationConfigResponse;
import com.novax.ex.activity.provider.controller.BaseActivityController;
import com.novax.ex.activity.provider.service.OperationConfigService;
import com.novax.ex.common.base.BaseEntity;
import com.novax.ex.common.constant.InternationalCode;
import com.novax.ex.common.results.ReturnResult;
import com.novax.ex.common.util.CopyUtils;
import com.novax.ex.common.util.PageUtil;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 活动落地页配置
 * @Author ChenXi
 * @Date 2023/04/18/10:08
 */

@RestController
public class OperationConfigInnerController extends BaseActivityController implements OperationConfigInnerApi {

    @Resource
    private OperationConfigService operationConfigService;

    @Override
    public ReturnResult<PageUtil<OperationConfigResponse>> page(String language, OperationConfigInnerQuery query) {
        PageUtil<OperationConfigResponse> pageInfo = new PageUtil<>(query);
        pageInfo.setCondition(Collections.singletonMap("query", query));
        operationConfigService.findPage(pageInfo, OperationConfigResponse.class);
        List<OperationConfigResponse> items = pageInfo.getItems();
        if (!items.isEmpty()) {
            List<Long> operationIds = items.stream().map(OperationConfigResponse::getId).map(Long::parseLong).collect(Collectors.toList());
            List<OperationUserCount> operationUserCounts = operationConfigService.countUserId(operationIds);
            // 如果没有查到
            if (operationUserCounts.isEmpty()) {
                items.forEach(item -> item.setCount(0));
            } else {
                Map<Long, Integer> countMap = operationUserCounts.stream()
                        .collect(Collectors.toMap(OperationUserCount::getOperationId, OperationUserCount::getCount));
                items.forEach(item -> item.setCount(countMap.get(Long.parseLong(item.getId()))));
            }
        }
        return ReturnResult.success(getInternational(language, InternationalCode.QUERY_SUCCESS), pageInfo);
    }

    @Override
    public ReturnResult<?> add(String language, OperationConfigRequest operationConfigRequest, BindingResult bindingResult) {
        // 缺少必填项
        if(bindingResult.hasErrors()){
            return ReturnResult.fail(getInternational(language, InternationalCode.LACK_VALUE));
        }
        OperationConfig operationConfig = CopyUtils.copyObject(operationConfigRequest, OperationConfig.class);
        operationConfig.setCustomId(getCustomId());
        operationConfig.setCreateTime(new Date());
        boolean res = operationConfigService.addSelective(operationConfig);
        return res ? ReturnResult.success(getInternational(language, InternationalCode.OPERATION_SUCCESS))
            : ReturnResult.fail(getInternational(language, InternationalCode.OPERATION_ERROR));
    }

    @Override
    public ReturnResult<?> modify(String language, Long operationId, OperationConfigRequest operationConfigRequest, BindingResult bindingResult) {
        // 缺少必填项
        if(bindingResult.hasErrors()){
            return ReturnResult.fail(getInternational(language, InternationalCode.LACK_VALUE));
        }
        OperationConfig operationConfig = CopyUtils.copyObject(operationConfigRequest, OperationConfig.class);
        operationConfig.setId(operationId);
        operationConfig.setUpdateTime(new Date());
        String note = operationConfig.getNote();
        // 为空也正常修改
        if(note  == null || note.equals("")){
            operationConfig.setNote(" ");
        }
        boolean res = operationConfigService.modifySelective(operationConfig);
        return res ? ReturnResult.success(getInternational(language, InternationalCode.OPERATION_SUCCESS))
            : ReturnResult.fail(getInternational(language, InternationalCode.OPERATION_ERROR));
    }

    @Override
    public ReturnResult<?> remove(String language, Long operationId) {
        OperationConfig operationConfig = operationConfigService.find(operationId);
        if(Objects.isNull(operationConfig)){
            return ReturnResult.fail(getInternational(language, InternationalCode.NOT_FOUND));
        }
        if (1 == operationConfig.getState()){
            return ReturnResult.fail(getInternational(language, InternationalCode.ACTIVITY_STATUS));
        }
        boolean res = operationConfigService.remove(operationId);
        return res ? ReturnResult.success(getInternational(language, InternationalCode.OPERATION_SUCCESS))
            : ReturnResult.fail(getInternational(language, InternationalCode.OPERATION_ERROR));
    }

    /***
     * @Description: 生成自定义id
     * @Author: ChenXi
     * @Date:  2023/4/18 15:34
     * @param
     * @return: java.lang.String
     **/
    private String getCustomId() {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder result = new StringBuilder();
        Random random = new Random();

        // 是否唯一
        boolean isUnique = false;

        while (!isUnique) {
            result.setLength(0);
            result.append("BM");
            for (int i = 0; i < 4; i++) {
                int index = random.nextInt(characters.length());
                result.append(characters.charAt(index));
            }
            Long count = operationConfigService.findByCustomId(result.toString());
            isUnique = (count == 0);
        }

        return result.toString();
    }



}
